#include <vector>

using std::vector;

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        int u = 0, d = m - 1, l = 0, r = n - 1;
        int counts = m * n;
        vector<int> ret;
        int i = 0, j = 0;
        do {
            while (j <= r) {
                ret.emplace_back(matrix[i][j]);
                j++;
            }
            if (ret.size() == counts) {
                break;
            }
            j--;
            i++;
            u++;
            while (i <= d) {
                ret.emplace_back(matrix[i][j]);
                i++;
            }
            if (ret.size() == counts) {
                break;
            }
            i--;
            j--;
            r--;
            while (j >= l) {
                ret.emplace_back(matrix[i][j]);
                j--;
            }
            if (ret.size() == counts) {
                break;
            }
            j++;
            i--;
            d--;
            while (i >= u) {
                ret.emplace_back(matrix[i][j]);
                i--;
            }
            if (ret.size() == counts) {
                break;
            }
            i++;
            j++;
            l++;
        } while (true);
        return ret;
    }
};